﻿using System.Linq;
using PersonaLibrary.Data;

namespace PersonaLibrary.ViewModel.OrganizationsViewModel
{
    public class OrganizationViewModel : LinqEditableItem<Organization, View.OrganizationView.ChangeOrganization>
    {
        private readonly Validation.ValidationItem<Organization> _parentOrganization = new Validation.ValidationItem<Organization>();
        
        public OrganizationViewModel(int id)
        {
            EditableItem = Context.Organizations.FirstOrDefault(x => ((Organization) x).Id == id);

            InitValidation();
        }

        public OrganizationViewModel()
        {
            EditableItem = new Organization();
            InitValidation();
        }

        private void InitValidation()
        {
            _parentOrganization.Source = Context.Organizations;
            _parentOrganization.ValidExpression = x => x.Name.StartsWith(_parentOrganization.ValidationValue);
            _parentOrganization.Selector = x => x.Name;
            if (EditableItem.ParentOrganization != null)
            {
                _parentOrganization.ValidationValue = EditableItem.Parent.Name;
                _parentOrganization.ValidateCommand.Execute(null);
                _parentOrganization.MoreThenOneCand = false;
            }
        }


        #region Public properties

        public Validation.ValidationItem<Organization> ParentOrganization
        {
            get
            {
                return _parentOrganization;
            }
        }

        #endregion

        #region Parent override

        public override void Dispose()
        {
        }

        public override bool CanCommit()
        {
            if (EditableItem == null) return false;
            return !string.IsNullOrEmpty(EditableItem.Name);
        }

        public override void Commit()
        {
			if (string.IsNullOrEmpty(_parentOrganization.ValidationValue))
			{
				//EditableItem.ParentOrganization = null;
				EditableItem.Parent = null;
			}
			else
			{
				if (!_parentOrganization.IsValid)
				{
					_parentOrganization.ValidateCommand.Execute(null);
					if (!_parentOrganization.IsValid)
					{
						System.Windows.MessageBox.Show("Ошибка валидации организации, проверьте правильность имени");
						return;
					}
				}
				else
					EditableItem.ParentOrganization =
						Context.Organizations.Single(x => x.Name == _parentOrganization.ValidationValue).Id;
			}

        	base.Commit();
        }

        #endregion
    }
}
